<?php
/** 
 * Copyright (c) 2012, Jiehun.com.cn Inc. All Rights Reserved
 * @author Ronnie(dengxiaolong@gmail.com)
 * @date 2012-9-16
 * @version 1.0
 * @brief 
 *  
 **/
require_once PAGE_ROOT.'/index/TsController.php';
class ActionController extends TsController
{
	protected $loadUser = false;
	
	function _upload()
	{
		$this->checkLogin();
		if (empty($_FILES['upload'])) {
			throw new Exception('image.u_fileIsNotSupplied name=upload');
		}
		$file = $_FILES['upload'];
		
		if ($file['error'] != 0) {
			throw new Exception('image.u_uploadError error='. $file['error']);
		}

		// 检测是否图片类型
		$path = $file['tmp_name'];
		if (@getimagesize($path) === FALSE) {
			throw new Exception('image.u_formatWrong');
		}
		

		$fileId = $this->uploadImage($file['tmp_name']);
		Logger::trace(var_export($fileId, true));

		$images = array();
		$images['orig'] = array(
			'id'	=> $fileId['hex'],
			'url'	=> $fileId['publicUrl'],
			'width'	=> $fileId['width'],
			'height'=> $fileId['height'],
		);

		$rules = array_unique(array_map('trim', explode(',', $this->get('rules'))));
		foreach($rules as $ruleName) {
			$info = $this->getImageInfo($fileId, $ruleName);
			if ($info) {
				$images[$ruleName] = $info;
			}
		}
		$this->response->rmset();
		$this->set('images', $images);
		
		$this->response->setHeader('Content-type:text/html;charset=utf-8');
	}
	
	function downpic()
	{
		$url = $this->get('url');
		if (!$url) {
			$this->show404();
		}
		$img= Com::get('image');
		$info = $img->parseUrl($url);
		
		if ($info === false || $info['type'] == 'origin') {
			$this->show404();
			return;
		}
		$imageId = $info['id'];
		$type = $info['type'];
		$width = $info['width'];
		$height = $info['height'];
		
		$conf = Conf::get('hapn.host');
		$cdnHost = $conf['cdn'];
		$staticHost = $conf['static'];
		if (!$imageId) {
			$this->response->redirect('http://'.$staticHost.'/static/img/default/picture.png');
		}
		
		// 下载的图片地址，用来解决图片下载出错时的跟踪
		Logger::addBasic(array('pu' => $url));
		$originPath = $img->getFilePath($imageId);
		if (!file_exists($originPath)) {
			$this->show404();
			return;
		}
			
		// 检查图片规格
		if (!$img->getRuleName($width, $height, $type)) {
			$this->show404();
			return;
		}
		
		// 是否需要打水印
		$watermark = $info['watermark'];
		if ($watermark && !$img->needWatermark($originPath)) {
			$this->show404();
			return;
		}
		
		$newUrl = $img->resize($imageId, $width, $height, $type, $watermark);
		if (!isset($newUrl)) {
			$this->response->redirect('http://'.$staticHost.'/static/img/default/picture.png');
		}
		$conf = Conf::get('hapn.com');
		$newPath = $conf['image']['savedir'].'/'.$newUrl;
		$imgInfo = getimagesize($newPath);
		$this->response->setHeader('Content-type: '. $imgInfo['mime']);
		$this->response->setRaw(file_get_contents($newPath));
	}
	
	private function show404()
	{
		$this->response->setHeader('HTTP/1.1 404 Not Found');
		$this->response->setRaw('');
	}
}